package com.aco.party.service.system;

import com.aco.party.dao.custom.MessageDao;
import com.aco.party.model.po.Message;
import com.aco.party.model.po.User;
import com.aco.party.model.vo.MessageParam;
import com.aco.party.model.vo.MessageVo;
import com.aco.party.model.vo.common.PageParam;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by flying on 3/10/2016 0010.
 */
@Service
public class MessageService {
    @Resource
    private MessageDao messageDao;

    @Resource
    private UserService userService;

    public List<MessageVo> getByPage(PageParam pageParam,MessageParam param) {
        List<MessageVo> list = new ArrayList<>();
        List<Message> messages = messageDao.getList(pageParam,param);
        MessageVo vo;
        if (messages != null) {
            for (Message message : messages) {
                vo = new MessageVo();
                BeanUtils.copyProperties(message, vo);
                if(vo.getTarget() != null){
                    User user = userService.getUser(vo.getTarget());
                    if(user != null)
                        vo.setTargetStr(user.getNickName());
                }
                if(vo.getCreator() != null && vo.getCreator() != 0)
                    vo.setCreatorStr(userService.getUser(vo.getCreator()).getNickName());
                list.add(vo);
            }
        }
        return list;
    }

    public Integer getTotal(MessageParam param) {
        return messageDao.getTotal(param);
    }

    public void update(Message message) {
        message.setUpdateTime(new Date());
        messageDao.updateByPrimaryKeySelective(message);
    }

    public void add(Message message) {
        message.setCreateTime(new Date());
        messageDao.insertSelective(message);
    }

    public void delete(Long id) {
        messageDao.deleteByPrimaryKey(id);
    }

    public Message getByPrimaryKey(Long id) {
        return messageDao.selectByPrimaryKey(id);
    }

    public void sendMsg(Long id, String title, String content) {
        Message message = new Message();
        message.setTarget(id);
        message.setTitle(title);
        message.setContent(content);
        message.setCreator(1L);
        this.add(message);
    }
}
